package com.link510.aitools.services;

import com.link510.aitools.core.errors.SateCollect;
import com.link510.aitools.core.listen.CWMListener;
import com.link510.aitools.core.message.MessageInfo;
import com.link510.aitools.data.CommandData;
import com.orhanobut.logger.Logger;

import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 命令
 */
public class Commands extends BaseService {

    private static Commands instance;

    public static Commands getInstance() {

        if (instance == null) {

            synchronized (Commands.class) {

                if (instance != null) {
                    return instance;
                }

                instance = new Commands();
            }

        }

        return instance;
    }


    /**
     * 发送命令
     *
     * @param deviceSN 设备编号
     * @param command  设备命令
     * @return 返回广告列表
     */
    public void send(String deviceSN, String command, CWMListener<MessageInfo<String>> listener) {

        try {

            CommandData.getInstance().get(deviceSN, command)
                    .subscribeOn(Schedulers.newThread())
                    .subscribe(messageInfo -> {
                        if (messageInfo == null) {
                            onErrorAction(listener, -3, "数据消息解析异常");
                            return;
                        }

                        if (!SateCollect.SUCCESS.equals(messageInfo.getState())) {
                            onErrorAction(listener, messageInfo.getState(), messageInfo.getMessage());
                            return;
                        }

                        onSuccessAction(listener, messageInfo.getMessage(), messageInfo);

                    }, (Consumer<Throwable>) t -> {
                        // 处理异常

                        try {
                            onErrorAction(listener, -2, "发送命令发生异常");
                            Logger.e(t, "发送命令发生异常");
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    });
        } catch (Exception ex) {
            Logger.e(ex, "发送命令发生异常");
            onErrorAction(listener, -1, "发送命令发生异常");
        }
    }
}
